package com.damage.purchase_dept.oa.sendOrder;

import com.damage.common.config.DepartmentConfig;
import com.damage.common.config.ProcessDefinitionConfig;
import com.damage.common.dto.OrderSender;
import com.damage.common.entity.Order;
import com.damage.common.exception.IdentityException;
import com.damage.common.exception.IncorrectStateException;
import com.damage.common.exception.ObsoleteException;
import com.damage.common.exception.RelateException;
import com.damage.common.oa.sendOrder.SendOrderConfig;
import com.damage.common.service.IPublicService;
import com.damage.purchase_dept.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class StartSendOrderService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private IOrderService orderService;

    @Transactional
    public Order startSendOrder(Integer orderId,OrderSender orderSender) throws IdentityException,RelateException{
        //验证身份
        User user = identityService.createUserQuery().userFirstName(orderSender.getSender()).singleResult();
        Group group = identityService.createGroupQuery().groupMember(user.getId()).singleResult();
        String groupId = group.getId();
        identityService.setAuthenticatedUserId(user.getId());
        if (!DepartmentConfig.purchaseDept.equals(groupId)) {
            throw new IdentityException("订单发送人的身份不是采购部的员工，不能启动流程！");
        }

        //发送订单
        try {
            orderService.sendOrder(orderId, orderSender);
        } catch (RelateException e) {
            throw e;
        }

        ProcessInstance processInstance = null;
        try {
            //启动流程
            Order order = orderService.findById(orderId);
            String businessKey = orderId.toString();
            Map<String, Object> vars = new HashMap<>();
            User supplier = identityService.createUserQuery().userFirstName(order.getOrderReceiver()).singleResult();
            vars.put(SendOrderConfig.SUPPLIER, supplier.getId());
            processInstance = runtimeService.startProcessInstanceByKey(ProcessDefinitionConfig.SEND_ORDER, businessKey,vars);
            String processInstanceId = processInstance.getId();
            orderService.setProcessInstanceId(order.getId(), processInstanceId);
            log.info("start process of {key={}, bkey={}, pid={}}", new Object[]{"sendOrder", businessKey, processInstanceId});
            return order;
        } finally {
            identityService.setAuthenticatedUserId(null);
        }
    }
}
